<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) 2015-2016 http://www.clcw.com.cn All rights reserved.    |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                          |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: Xmh <xiangminghu@clcw.com.cn>                                  |
// +------------------------------------------------------------------------+
//

namespace AuctionAppApi\Controller;

use Think\Controller;
use AuctionCore\System\AuctionException;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\Common\PhpMemcache;
use AuctionCore\Common\AntNest;
use AuctionCore\Account\UniqLogin;
use AuctionCore\Common\PhpRedis;
use AuctionCore\System\AppDevice;
use AuctionCore\Account\LoginLog;
use AuctionCore\Common\Des;
use AuctionCore\Common\Image;
use AuctionCore\Common\Util;

/**
 * 车商相关信息
 *
 * @author Xmh
 */
class AuthController extends BaseController {

    public function __construct() {
        parent::__construct();        
    }

    
    public function login() {
        $username = I('post.username');
        $login_key = I('post.key');
        $is_no_encrypt = I('post.is_no_encrypt'); 
        $jpush_id = I('post.jpush_id');
       
        list($info,$key) = Dealer::loginByLoginKey($username,$login_key,$this->time);

        //des加密结果传输
        if(!$key) 
           AuctionException::make_throw('300009');
        $key = substr($key,0,8);
        $info['token'] = md5($info['uniq_login_token']);

        //登录uniq_login_token
        $redis = new PhpRedis();
        $left_time = strtotime(date('Y-m-d 00:00:00',strtotime('+1 day')))-time();
        $uniq_login_token = $info['uniq_login_token'] ;
        $arr = [
            'uuid'=>$this->uuid,
            'uid'=>$info['uid']
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY','100003',$arr);
        $redis->set($keyName , $info['uniq_login_token'] ,$left_time);
        unset($info['uniq_login_token']);

        //记录设备id
        $dev = new AppDevice();
        $dev_info = array('dev_uuid'=>$this->uuid,'dev_uid'=>$info['uid'],'dev_jpush_id'=>$jpush_id);
        $ok = $dev->save($dev_info);

        //记入登录日志
        if(isset($info['uid'])){
            LoginLog::save($info['uid'],($this->is_ios?2:1),sha1($uniq_login_token),get_client_ip());
        }

        if($is_no_encrypt){
            //不加密返回结果
            $this->api_200($info);    
        }else{
            //加密返回结果            
            $crypt = new Des($key);
            $encrypt = $crypt->encrypt($key, json_encode($info,true));
            $this->api_200($encrypt);    
        }        
    }

    /**
     * @throws AuctionException
     */
    public function login_v2(){
        $username = I('post.username');
        $login_key = I('post.key');
        $is_no_encrypt = I('post.is_no_encrypt');
        $jpush_id = I('post.jpush_id');

        $rsa_data = self::dico_rsa($login_key);
        $is_md5 = is_md5($rsa_data);
        if( !$is_md5 ) exit(json_encode(array('code'=>500,'msg'=>'系统错误')));
        if(!$rsa_data){
            AuctionException::make_throw('150009');
        }
        $this->public_login($username,$rsa_data,$login_key,$jpush_id,$is_no_encrypt);

    }

    public function logout(){
        $redis = new PhpRedis();
        $arr = [
            'uuid'=>$this->uuid,
            'uid'=>$this->uid
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY','100003',$arr);
        $redis->del($keyName);
        $this->api_200('');
    }

    /**
     * 获取加密数据
     * @param string $data
     * @return bool
     */
    public static function dico_rsa($data = ''){
        $system = new SystemController();
        $private_key = $system->getKey(2);
        $private_key = openssl_get_privatekey($private_key);
        $info = '';
        openssl_private_decrypt(base64_decode($data),$info,$private_key);
        return $info;
    }

    /**
     * 客户经理查询
     */
    public function get_manager(){
    //    $city = I('post.city_code');
        $mobile = I('post.mobile');
        if(empty($mobile)) exit(json_encode(array('code'=>500,'msg'=>'参数错误')));
        $emp = M('employee')->where("mobile = '".$mobile."'")->field('real_name,province_id')->find();
        //查询客户经理信息
        if($emp){
            exit(json_encode(array('code'=>200,'data'=>$emp['real_name'])));
        }
        exit(json_encode(array('code'=>500,'msg'=>'查无此人')));
    }


    /**
     * 注册
     */
   public  function regist(){
        $login_key = I('post.key');
        $is_no_encrypt = I('post.is_no_encrypt');
        $jpush_id = I('post.jpush_id');
        $data     = I('post.data');
        $v_code   = I('post.v_code');
        $mobile   = I('post.mobile');
        $city_code   = I('post.city_code');
        $cm_mobile   = I('post.cm_mobile');
        $number      = 13;
        $rsa_data = self::dico_rsa($login_key);
        //校验传输密码是否正确
        $is_md5 = is_md5($rsa_data);
        if( !$is_md5 ) exit(json_encode(array('code'=>500,'msg'=>'系统错误')));
        if((!$rsa_data) ||  empty($jpush_id) || empty($v_code) || empty($mobile) || empty($city_code)){
            exit(json_encode(array('code'=>500,'msg'=>'输入有误，请重新输入')));
        }
        //手机校验
        $ant = new AntNest();
      //  $is_reg = $ant->verify_mobile(array('mobile'=>$data['mobile']));
      //  if($is_reg['code']=='000000'){
      //      exit(json_encode(array('code'=>500,'msg'=>'手机号已被注册')));
      //  }

        $option['ver_code'] = $v_code;
        $option['number'] =  $number;
        $option['mobile'] = $mobile;
        $vCode = $ant->sms_verify($option);
        if($vCode){
            $option['pwd'] = $rsa_data;
            $option['cm_mobile'] = $cm_mobile;
            $option['city_code'] = $city_code;
//            $username = $option['account_name'] =  C('ANT_USERNAME_PREFIX').$option['mobile'];
            $userinfo = Dealer::create($option);
            if($userinfo['code']=='000000'){
                $this->public_login($userinfo['data']['account_name'],$rsa_data,$login_key,$jpush_id,$is_no_encrypt);
            }
            exit(json_encode(array('code'=>500,'msg'=>$userinfo['msg'])));
        }
        exit(json_encode(array('code'=>500,'msg'=>'校验码错误')));
    }

    /**
     * 找回密码
     * @throws AuctionException
     */
    public function  reset_pwd(){
        $login_key  = I('post.key');
        $v_code     = I('post.v_code');
        $number     =  I('post.number');
        $mobile     = I('post.mobile');
        $is_no_encrypt = I('post.is_no_encrypt');
        $jpush_id      = I('post.jpush_id');
        if(empty($v_code) || empty($mobile) || empty($number)){
            exit(json_encode(array('code'=>500,'msg'=>'输入有误，请重新输入')));
        }
        //手机验证码校验
        $ant = new AntNest();
        $option['ver_code'] = $v_code;
        $option['number']   =   $number;
        $option['mobile']   = $mobile;
        $rsa_data = self::dico_rsa($login_key);

        if ($rsa_data == md5('123456')) {
            AuctionException::make_throw('200040');
        }

        //校验传输密码是否正确
        $is_md5 = is_md5($rsa_data);
        if( !$is_md5 ) exit(json_encode(array('code'=>500,'msg'=>'系统错误')));
        if(!$rsa_data){
            AuctionException::make_throw('-10007');
        }
        $option['ver_code'] = $v_code;
        $option['number'] =  $number;
        $option['mobile'] = $mobile;
        $vCode = $ant->sms_verify($option);
        if($vCode){
            $option['pwd_new'] = $rsa_data;
            $info = $ant->retrieve_pwd($option);
            if($info['code']==='000000'){
                //启用登录服务
              //  echo $mobile."|".$rsa_data.'|'.$login_key;die;
                $this->public_login($mobile,$rsa_data,$login_key,$jpush_id,$is_no_encrypt);
            }else{
                exit(json_encode(array('code'=>$info['code'],'msg'=>$info['msg'])));
            }
        }else{
            exit(json_encode(array('code'=>500,'msg'=>'验证码错误')));
        }
    }

    /**
     * 登录、找回密码公用方法  调用蚁巢服务并检测信息和存储信息 返回；
     * @param $username
     * @param $rsa_data
     * @param $login_key
     * @param $jpush_id
     * @param $is_no_encrypt
     * @throws AuctionException
     */
    private function public_login($username,$rsa_data,$login_key,$jpush_id,$is_no_encrypt){
        if(empty($username)|| empty($rsa_data) || empty($login_key)){
            AuctionException::make_throw('1200002');
        }
        //蚁巢服务
        $ant = new AntNest();

        $result = $ant->ant_login($username,$rsa_data);

        if($result['code']==='000000'){

            //数据解析
            $info = $result;

            //若密码为123456强制跳转到密码修改页面
            $info['force_repwd'] = false;
            if($rsa_data  == md5('123456')){
                $info['force_repwd'] = true;
            }

            $mem = new PhpMemcache();
            if($mem->get('appapi_login_'.$login_key) || (time()-($this->time/1000))>30){
                AuctionException::make_throw('100068');
            }
            $dealer = new Dealer($this->dealer_id);
            $key = substr($rsa_data,0,8);

            $info = $dealer->login_info($info,$login_key,$this->is_ios,$this->uuid,$jpush_id);
            if($is_no_encrypt){
                //不加密返回结果
                $this->api_200($info);
            }else{
                //加密返回结果
                $crypt = new Des($key);
                $encrypt = $crypt->encrypt($key, json_encode($info,true));
                $this->api_200($encrypt);
            }
        }else{
            AuctionException::make_throw($result['code'],$result['msg']);
        }
   }




    /*
     * 图片上传接口
     */
    public function upload_image()
    {
        $rep = array('code' => 200);
        $file = I('data.pic', '', '', $_FILES);
        $md5 = I('request.md5');
        $flag = true;

//        if(empty(I('data.pic'))){
//            $flag = false;
//            $rep['code'] = 430;
//            $rep['msg'] = '照片上传失败';
//        }
        if ($file['error'] != 0) {
            $flag = false;
            $rep['code'] = 430;
            $rep['msg'] = '照片上传失败';
            trace($rep['msg'] . ',错误码：' . $file['error'] . ',time:' . date('Y-m-d H:i:s'),'','ERR',true);
        }
        //图片上传
        if ($flag) {
            $ext = get_extension($file['name']);
            $object = create_uuid() . '.' . ($ext ? $ext : 'jpg');
            $file_path = $file['tmp_name'];
            try {
                if (strtolower($md5) != md5_file($file_path)) {
                    $rep['code'] = 430;
                    $rep['msg'] = '验证错误';
                } else {
                    $aliObject = Image::upload_file_by_file(OSS_BUCKET, $object, $file_path,null,'','car_dealer');
                    $host = get_content_cdnurl();
                    $rep['data'] = $host . $aliObject;
                }
            } catch (\Exception $e) {
                $rep['code'] = 430;
                $rep['msg'] = $e->getMessage();
            }
        }
        echo json_encode($rep);
        exit;
    }

    /**
     * 车商签约认证
     */
    public function auth_sign(){
        //认证类型
        $auth_type = I('request.auth_type');

        //个人
        $name = I('request.name');//姓名（或授权人）
        $idcard = I('request.idcard');//身份证号
        $idcard_front_pic = replace_url(I('request.idcard_front_pic'));//身份证正面
        $idcard_back_pic = replace_url(I('request.idcard_back_pic'));//身份证背面
        $idcard_hold_pic = replace_url(I('request.idcard_hold_pic'));//身份证手持照
        $mobile = I('request.mobile');//手机
        $m = I('request.m');

        //企业
        $is_three_in_one = I('request.is_three_in_one');//是否三证合一
        $company_name = I('request.company_name');//公司名称
        $business_license_num = I('request.business_license_num');//营业执照号
        $organization_code = I('request.organization_code');//组织机构代码
        $tax_reg_cert_no = I('request.tax_reg_cert_no');//税务登记证号
        $business_license_pic = replace_url(I('request.business_license_pic'));//营业执照照片
        $organization_code_pic = replace_url(I('request.organization_code_pic'));//组织机构代码证照片
        $tax_reg_cert_pic = replace_url(I('request.tax_reg_cert_pic'));//税务登记证照片
        $auth_letter_pic = replace_url(I('request.auth_letter_pic'));//授权委托书照片
        //检查是否已认证过
        $dealer  = new Dealer($this->dealer_id);
        $dealer_info = $dealer->detail();
        if(in_array($dealer_info['auth_status'],array('1','2'))){
            AuctionException::make_throw('160001');
        }

        //
        $data = array();
        $data['contact_person'] = $name;
        $ant = new AntNest();
        $user_info = $ant->get_userinfo($this->uid);
        //$data['contact_mobile'] = $mobile?$mobile:$user_info['pwd_mobile'];
        $data['dealer_idcard'] = $idcard;
        $data['idcard_front_pic'] = $idcard_front_pic;
        $data['idcard_back_pic'] = $idcard_back_pic;
        $data['idcard_hold_pic'] = $idcard_hold_pic;

        $data['category'] = 1;//正式账号

        if($auth_type=='1'){
            if(empty($name)){
                AuctionException::make_throw('160002');
            }
            if(empty($idcard)){
                AuctionException::make_throw('160003');
            }
            /**校验身份证是否已注册  add by wangji  20161129**/
            $is_sign = $dealer->check_dealer_sign(array('auth_type'=>$auth_type,'dealer_idcard'=>$idcard,'status'=>1));
            if($is_sign){
                AuctionException::make_throw('160024');
            }
            /**end***/
            $iv_code = idcard_verify($name,$idcard);
            if($iv_code != '1000'){
                AuctionException::make_throw('160021');
            }
            if(empty($idcard_front_pic)){
                AuctionException::make_throw('160004');
            }
            if(empty($idcard_back_pic)){
                AuctionException::make_throw('160005');
            }
            if(empty($idcard_hold_pic)){
                AuctionException::make_throw('160006');
            }
            $data['auth_type'] = 1;
            $data['auth_status'] = 2;
            if(!$m){
                $data['apply_auth_time'] = date('Y-m-d H:i:s');
                $data['auth_audit_time'] = date('Y-m-d H:i:s');
            }

        }elseif($auth_type=='2'){
            if(empty($company_name)){
                AuctionException::make_throw('160007');
            }
            /**校验组织代码，营业执照code、税务登记code是否已注册  add by wangji  20161129**/
            $option = array(
                'auth_type'=>$auth_type,
                'status'=>1,
                'business_license_num'=>$business_license_num
            );

            /**end***/
            if($is_three_in_one){
                if(empty($business_license_num)){
                    AuctionException::make_throw('160023');
                }
                $is_sign = $dealer->check_dealer_sign($option);
                if($is_sign){
                    $msg = AuctionException::$codes['160026'];
                    echo Util::auto_jsonp_or_json($_REQUEST,array('code'=>'160026','msg'=>$msg));
                    exit;
                }
            }else{
                if(empty($business_license_num)){
                    AuctionException::make_throw('160008');
                }
                $is_sign = $dealer->check_dealer_sign($option);
                if($is_sign){
                    $msg = AuctionException::$codes['160025'];
                    echo Util::auto_jsonp_or_json($_REQUEST,array('code'=>'160025','msg'=>$msg));
                    exit;
                }
                if(empty($organization_code)){
                    AuctionException::make_throw('160009');
                }
                if(empty($tax_reg_cert_no)){
                    AuctionException::make_throw('160010');
                }

                if(empty($organization_code_pic)){
                    AuctionException::make_throw('160015');
                }
                if(empty($tax_reg_cert_pic)){
                    AuctionException::make_throw('160016');
                }
            }
            if(empty($name)){
                AuctionException::make_throw('160011');
            }
            if(empty($idcard)){
                AuctionException::make_throw('160012');
            }
            $iv_code = idcard_verify($name,$idcard);
            if($iv_code!='1000'){
                \Think\Log::record('身份证验证返回CODE：'.$iv_code);
                AuctionException::make_throw('160021');
            }
//            if(empty($mobile)){
//                AuctionException::make_throw('160013');
//            }
//            if(!isMobile($mobile)){
//                AuctionException::make_throw('200071');
//            }
            if(empty($idcard_front_pic)){
                AuctionException::make_throw('160017');
            }
            if(empty($idcard_back_pic)){
                AuctionException::make_throw('160018');
            }
            if(empty($idcard_hold_pic)){
                AuctionException::make_throw('160019');
            }
            if(empty($business_license_pic)){
                AuctionException::make_throw('160014');
            }
            if(empty($auth_letter_pic)){
                AuctionException::make_throw('160020');
            }


            $data['is_three_in_one'] = $is_three_in_one>0?1:0;
            $data['fullname'] = $company_name;
            $data['business_license_num'] = $business_license_num;
            $data['organization_code'] = $organization_code;
            $data['tax_reg_cert_no'] = $tax_reg_cert_no;

            $data['business_license_pic'] = $business_license_pic;
            $data['organization_code_pic'] = $organization_code_pic;
            $data['tax_reg_cert_pic'] = $tax_reg_cert_pic;
            $data['auth_letter_pic'] = $auth_letter_pic;


            $data['auth_status'] = 1;
            $data['auth_type'] = 2;

        }else{
            AuctionException::make_throw('160000');
        }
        //申请认证时间
        $data['apply_auth_time'] = date('Y-m-d H:i:s');

        //认证
        M()->startTrans();
        $ret = $dealer->update($data,$this->uid,$error_info);

        //如果有被跟踪记录，则更新记录表字段certify_result=3（跟踪待认证成功），
        $cnt = $dealer->get_certify_log_stat();
        if($cnt>0){
            $ret1 = $dealer->edit(array('wait_auth_trace_status'=>3));
            $ret2 = $dealer->update_certify_log(array('certify_result'=>3));
            if($ret1 === false || $ret2 === false){
                M()->rollback();
                trace('更新车商认证记录表失败','','ERR',true);
            }
        }

        if(!$ret){
            if($error_info){
                echo Util::auto_jsonp_or_json($_REQUEST,array('code'=>$error_info['code'],'msg'=>$error_info['msg'],'data'=>''));
                exit;
            }else{
                AuctionException::make_throw('160022');
            }
        }

        M()->commit();
        //
        $this->api_200(null);
    }

    //签约
    public function protocol(){
        $agree = I('request.agree');

        $dealer  = new Dealer($this->dealer_id);
        $dealer_info = $dealer->detail();

        if(!$dealer_info['is_agree_agreement']){
            if($agree==1){
                M()->startTrans();
                $sign_contract_no = date('Y').str_pad($this->dealer_id,5,0);
                $ok = $dealer->edit(array('sign_time'=>date('Y-m-d H:i:s'),'sign_contract_no'=>$sign_contract_no,'is_agree_agreement'=>1,'level'=>1));
                if($ok === false){
                    echo Util::auto_jsonp_or_json($_REQUEST,array('code'=>'100066','msg'=>'操作失败'));
                    exit;
                }
                $cnt = $dealer->get_sign_log_stat();
                if($cnt>0){
                    $ret1 = $dealer->edit(array('sign_trace_status'=>3));
                    $ret2 = $dealer->update_sign_log(array('sign_result'=>3));
                    if($ret1 === false || $ret2 === false){
                        M()->rollback();
                        trace('更新车商认证记录表失败','','ERR',true);
                        AuctionException::make_throw('100066');
                    }
                }
                M()->commit();
                echo Util::auto_jsonp_or_json($_REQUEST,array('code'=>'200','msg'=>'SUCCESS'));
                exit;
            }
        }

        $this->assign('dealer_info',$dealer_info);
        $this->api_200(null);

    }
    //获取车商认证信息
    public function auth_info(){
        $dealer  = new Dealer($this->dealer_id);
        $dealer_info = $dealer->detail();
        $data = array();
        $data['is_three_in_one'] = $dealer_info['is_three_in_one']?true:false;
        $data['person_name'] = $dealer_info['contact_person'];
        $data['company_name'] = $dealer_info['fullname'];
        $data['idcard'] = $dealer_info['dealer_idcard'];
        $data['idcard_front_pic'] = get_content_cdnurl().$dealer_info['idcard_front_pic'];
        $data['idcard_back_pic'] = get_content_cdnurl().$dealer_info['idcard_back_pic'];
        $data['idcard_hold_pic'] = get_content_cdnurl().$dealer_info['idcard_hold_pic'];
        $data['mobile'] = $dealer_info['contact_mobile'];
        $data['business_license_num'] = $dealer_info['business_license_num'];
        $data['organization_code'] = $dealer_info['organization_code'];
        $data['tax_reg_cert_no'] = $dealer_info['tax_reg_cert_no'];
        $data['business_license_pic'] = get_content_cdnurl().$dealer_info['business_license_pic'];
        $data['organization_code_pic'] = get_content_cdnurl().$dealer_info['organization_code_pic'];
        $data['tax_reg_cert_pic'] = get_content_cdnurl().$dealer_info['tax_reg_cert_pic'];
        $data['auth_letter_pic'] = get_content_cdnurl().$dealer_info['auth_letter_pic'];
        $this->api_200($data);
    }
    //获取车商认证信息
    public function auth_state(){
        $with_detail = I('request.with_detail');
        $dealer  = new Dealer($this->dealer_id);
        $dealer_info = $dealer->detail();

        $data = array();
        if($dealer_info['is_agree_agreement']){//是否已签约
            $data['state'] = '4';
            $list = array();
            if($dealer_info['auth_type']==1){//个人
                $list[] = array('name'=>'姓名','value'=>$dealer_info['contact_person']);
                $list[] = array('name'=>'身份证','value'=>$this->encrypt_str($dealer_info['dealer_idcard']));
                $list[] = array('name'=>'认证类型','value'=>'个人认证');
                $list[] = array('name'=>'认证签约状态','value'=>'已完成');
            }elseif($dealer_info['auth_type']==2){//企业
                $list[] = array('name'=>'公司名称','value'=>$dealer_info['fullname']);
                $list[] = array('name'=>'营业执照','value'=>$this->encrypt_str($dealer_info['business_license_num']));
                $list[] = array('name'=>'组织机构代码','value'=>$this->encrypt_str($dealer_info['organization_code']));
                $list[] = array('name'=>'税务登记证号','value'=>$this->encrypt_str($dealer_info['tax_reg_cert_no']));
                $list[] = array('name'=>'代理人姓名','value'=>$dealer_info['contact_person']);
                $list[] = array('name'=>'代理人身份证','value'=>$this->encrypt_str($dealer_info['dealer_idcard']));
                $list[] = array('name'=>'认证类型','value'=>'企业认证');
                $list[] = array('name'=>'认证签约状态','value'=>'已完成');
            }
            $data['list'] = $list;
        }else{
            switch($dealer_info['auth_status']){
                case '0'://未认证
                    $data['state'] = '0';
                    $data['state_name'] = '立刻认证';
                    break;
                case '1'://审核中
                    $data['state'] = '1';
                    $data['state_name'] = '认证审核中';
                    if($with_detail){
                        $data['apply_time'] = date('Y-m-d H:i',strtotime($dealer_info['apply_auth_time']));
                        $data['msg'] = "1. 我们将在1个工作日内完成审核。\n2. 认证结果可以在“账户中心页－认证签约”查看。\n3. 审核失败时，可以查看失败原因。更新认证信息后，可以重新提交认证审核。\n4. 审核通过后，可以继续进行申请签约。\n";
                    }
                    break;
                case '2'://审核通过
                    $data['state'] = '3';
                    $data['state_name'] = $dealer_info['auth_type']==1?'个人签约':'企业签约';
                    break;
                case '3'://审核失败
                    $data['state'] = '2';
                    $data['state_name'] = '认证失败';
                    if($with_detail){
                        $dealer_fail_log = $dealer->get_auth_sign_fail_log();
                        $data['msg'] = $dealer_fail_log['remark'];
                    }
                    break;
            }

        }

        $this->api_200($data);
    }

    /**
     * @param $str
     * @return string
     */
    private function encrypt_str($str){
        if(empty($str))return '';
        if(strlen($str)<3)return $str;
        $s = '';
        $s .= substr($str,0,1);
        $s .= str_pad('',strlen($str)-2,'*');
        $s .= substr($str,strlen($str)-1,1);
        return $s;
    }
}
